package com.lvcoding.sec3.secdemo3.security.sms;

import com.lvcoding.sec3.secdemo3.security.LoginFailHandler;
import com.lvcoding.sec3.secdemo3.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @description 描述
 * @date   2022-03-10 下午8:05
 * @author  wuyanshen
 */
// @Component
public class SmsAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private LoginFailHandler loginFailHandler;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired
    @Qualifier("smsUserDetailService")
    private UserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 添加登录成功处理器
        smsAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        // 添加登录失败处理器
        smsAuthenticationFilter.setAuthenticationFailureHandler(loginFailHandler);
        //把smsAuthenticationFilter过滤器添加在UsernamePasswordAuthenticationFilter之前
        http.addFilterAfter(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
        smsAuthenticationProvider.setUserDetailsService(userDetailsService);

        // 短信验证码
        http.authenticationProvider(smsAuthenticationProvider);

    }
}
